<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="8" :lg="7" :md="8" :sm="24">
            <a-form-item label="记录编号">
              <j-input placeholder="请输入记录编号" v-model="queryParam.recordNo"></j-input>
            </a-form-item>
          </a-col>
          <a-col :xl="8" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">

      <a-button type="primary" icon="download" @click="handleExportXlsTemplate('商品批量导入模板')">
        下载模板
      </a-button>

      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="importHeader"
                :action="importExcelUrlSimple"
                @change="handleImportExcel">
        <a-button type="primary" icon="import">商品导入</a-button>
      </a-upload>

    </div>

    <!-- table区域-begin -->
    <div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        class="j-table-force-wrap"
        @change="handleTableChange">

        <template slot="statusSlot" slot-scope="text">
          <a-tag color="red" v-if="text===0">
            进行中
          </a-tag>
          <a-tag color="green" v-else>
            已完成
          </a-tag>
        </template>

        <template slot="errorMsgSlot" slot-scope="text,record,index">
          <a-popconfirm
            title="确定下载错误信息嘛?"
            ok-text="是的"
            cancel-text="取消"
            @confirm="handleExportXls('批量商品导入失败信息',record.id)"
          >
            <a> {{ !text ? "错误信息下载" : text }}</a>
          </a-popconfirm>
        </template>

      </a-table>
    </div>

  </a-card>
</template>

<script>

import '@/assets/less/TableExpand.less';
import {mixinDevice} from '@/utils/mixin';
import {JeecgListMixin} from '@/mixins/JeecgListMixin';
import {BoneCommonMixin} from "@/mixins/BoneCommonMixin";
import Vue from "vue";
import {ACCESS_TOKEN} from "@/store/mutation-types";
import {Modal} from "ant-design-vue";
import store from "@/store";
import {downFile} from "@api/manage";

export default {
  name: 'GmsGoodsImportList',
  mixins: [JeecgListMixin, mixinDevice, BoneCommonMixin],
  components: {},
  data() {
    return {
      description: '商品的批量导入管理页面',
      routerPath: "/good/mng/GmsGoodsImportList",// 用于组件之间路由的路径 请在配置菜单完成之后添加 方便路由
      // 表头
      columns: [
        {
          title: '记录编号',
          align: "center",
          dataIndex: 'recordNo'
        },
        {
          title: '操作时间',
          align: "center",
          dataIndex: 'createTime',
        },
        {
          title: '完成时间',
          align: "center",
          dataIndex: 'updateTime',
        },
        {
          title: '操作人',
          align: "center",
          dataIndex: 'createBy',
        },
        {
          title: '导入的数量',
          align: "center",
          dataIndex: 'importNum'
        },
        {
          title: '成功数量',
          align: "center",
          dataIndex: 'successNum'
        },
        {
          title: '失败数量',
          align: "center",
          dataIndex: 'errorNum'
        },
        {
          title: '状态',
          align: "center",
          dataIndex: 'status',
          scopedSlots: {customRender: 'statusSlot'}
        },
        {
          title: '失败原因',
          align: "center",
          dataIndex: 'errorMessage',
          scopedSlots: {customRender: 'errorMsgSlot'}
        },
      ],
      url: {
        list: "/mallBase/gmsGoodsImport/list",
        exportXlsUrl: "/mallBase/gmsGoodsImport/exportXls",
        exportXlsTemplate: "/mallBase/gmsGoodsImport/exportXlsTemplate",
        importExcelSimple: "/mallBase/gmsGoodsImport/importExcelSimple",
      },
      dictOptions: {},
      /* 排序参数 */
      isorter: {
        column: 'createTime',
        order: 'desc',
      },
      queryParam: {
        sysOrgCode: this.orgCode,
      },
      disableMixinCreated: true,
    }
  },
  created() {
    this.queryParam.sysOrgCode = this.orgCode;
    this.loadData();
  },
  computed: {
    importExcelUrlSimple: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelSimple}`
    },
    importHeader() {
      let head = {'X-Access-Token': Vue.ls.get(ACCESS_TOKEN)}
      //当前用户店铺类型1:平台，2：自营，3：店铺，4：供应商
      let shopType = this.shopType;
      if (shopType) {
        head['shopType'] = shopType;
      }
      //当前用户部门code
      let orgCode = this.orgCode;
      if (orgCode) {
        head['orgCode'] = orgCode;
      }
      return head;
    }
  },
  methods: {
    searchReset() {
      this.queryParam = {sysOrgCode: this.orgCode,};
      this.loadData(1);
    },
    handleExportXlsTemplate: function (fileName) {
      downFile(this.url.exportXlsTemplate, {fileName: fileName}).then(data => {
        if (!data) {
          this.showError("模板下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], {type: 'application/vnd.ms-excel'}), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], {type: 'application/vnd.ms-excel'}))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      });
    },
    handleExportXls(fileName, id) {
      downFile(this.url.exportXlsUrl, {id: id}).then((data) => {
        if (!data) {
          this.showWarn("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], {type: 'application/vnd.ms-excel'}), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], {type: 'application/vnd.ms-excel'}))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    handleImportExcel(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          // this.showSuccess(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 201) {
            let {message, result: {msg, fileUrl, fileName}} = info.file.response
            let href = window._CONFIG['domianURL'] + fileUrl
            this.$warning({
              title: message,
              content: (<div>
                  <span>{msg}</span><br/>
                  <span>具体详情请 <a href={href} target="_blank" download={fileName}>点击下载</a> </span>
                </div>
              )
            })
          } else {
            this.showSuccess(info.file.response.message || `${info.file.name} 文件上传成功`);
          }
          this.loadData();
        } else {
          this.showError(`${info.file.name} ${info.file.response.message}.`)
          this.loadData();
        }
      } else if (info.file.status === 'error') {
        if (info.file.response.status === 500) {
          let data = info.file.response
          const token = Vue.ls.get(ACCESS_TOKEN)
          if (token && data.message.includes("Token失效")) {
            Modal.error({
              title: '登录已过期',
              content: '很抱歉，登录已过期，请重新登录',
              okText: '重新登录',
              mask: false,
              onOk: () => {
                store.dispatch('Logout').then(() => {
                  Vue.ls.remove(ACCESS_TOKEN)
                  window.location.reload()
                })
              }
            })
          }
        } else {
          this.showError(`文件上传失败: ${info.file.msg} `)
        }
      }
    },
  }
}
</script>
<style scoped>
</style>
